/**
 * 封装了数组，为了快速查找需求。
 * 因为记录了key对应的位置
 * 所以查找很快。
 */
export default class TSList<T>  {


    private keyMap = {}
    private list: { key: string | number, value: T }[] = [];
    // private indexList:any[] = [];
    // private count:number = 0;


    /**
     * 
     */
    clear() {
        this.keyMap = {}
        this.list = []
        // cc.log(' clear ==========  ')
        // this.count = 0;
    }

    /**
     * 
     */
    size(): number {
        return this.list.length;
    }

    /**
     * 
     */
    getList():{ key: string | number, value: T }[]{
        return this.list;
    }

    /**
     * 
     * @param key 
     * @param value 
     * @param index 
     */
    put(key: string | number, value: T,index:number = this.list.length) {
        // key = ''+key;
        // cc.log('put   =======   ',key);
        // cc.log('put ',this.keyMap)
        if (this.keyMap[key]) {
            cc.warn(' CgwMap 对象已经存在', key)
            return;
        }
        // this.list.push({ key: key, value: value });
        for (let i = index; i < this.list.length; i++) {
            const element = this.list[i];
            this.keyMap[element.key] ++;
        }           
        this.list.splice(index,0,{ key: key, value: value });
        // let index = this.list.length - 1;
        this.keyMap[key] = index
        // this.indexList[index] = key;
        // this.count ++;
    }

    /**
     * 
     * @param func 
     */
    forEach(func: (value: T,key: string | number) => void) {
        for (let index = 0; index < this.list.length; index++) {
            const element = this.list[index];
            func(element.value,element.key)
        }
    }

    /**
     * 
     * @param key 
     */
    get(key: string | number): T {
        // key = ''+key;
        let index = this.keyMap[key];
        if (index >= 0 && index < this.list.length) {
            return this.list[index].value;
        }
        return null;

    }
  
    /**
     * 
     * @param index 
     */
    removeIndex(index:number){
        if (index >= 0 && index < this.list.length) {
            let temp = this.list[index]
            this.list.splice(index, 1);
           
            for (let i = index; i < this.list.length; i++) {
                const element = this.list[i];
                this.keyMap[element.key] --;
            }
            delete this.keyMap[temp.key];
            return temp.value;
        } else {
            cc.warn(' 超出边界 ', index)
        }
    }

    /**
     * 
     * @param key 
     */
    removeKey(key: string | number): T {
        // key = ''+key;
        let index = this.keyMap[key];
        this.removeIndex(index);
       
        return null;
    }


    has(key: string | number): boolean {
        // key = ''+key;
        return this.keyMap[key] != undefined;
    }


}
